package db

import (
	"encoding/json"

	"github.com/samber/oops"
	bolt "go.etcd.io/bbolt"

	"github.com/aquasecurity/trivy-db/pkg/types"
)

const (
	vulnerabilityBucket = "vulnerability"
)

func (dbc Config) PutVulnerability(tx *bolt.Tx, cveID string, vuln types.Vulnerability) error {
	if err := dbc.put(tx, []string{vulnerabilityBucket}, cveID, vuln); err != nil {
		return oops.With("vuln_id", cveID).Wrapf(err, "failed to put severity")
	}
	return nil
}

func (dbc Config) GetVulnerability(cveID string) (vuln types.Vulnerability, err error) {
	eb := oops.With("vuln_id", cveID)
	err = db.View(func(tx *bolt.Tx) error {
		bucket := tx.Bucket([]byte(vulnerabilityBucket))
		value := bucket.Get([]byte(cveID))
		if value == nil {
			return eb.Errorf("no vulnerability details")
		}
		if err = json.Unmarshal(value, &vuln); err != nil {
			return eb.Wrapf(err, "json unmarshal error")
		}
		return nil
	})
	if err != nil {
		return types.Vulnerability{}, eb.Wrapf(err, "failed to get vulnerability")
	}
	return vuln, nil
}
